using System.Collections;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;
using System.IO;
using UnityEditor;

namespace HerenityCode.Reference
{
    namespace FileSystem
    {
        public class FileManager
        {
            /// <summary>
            /// 创建文件夹
            /// </summary>
            /// <param name="filePath">文件夹路径</param>
            /// <param name="fileName">文件夹名</param>
            public static void CreatFolder(string filePath, string fileName)
            {
                var file = Path.Combine(filePath, fileName);
                //判断文件夹路径是否存在
                if (!Directory.Exists(file))
                {
                    //创建
                    Directory.CreateDirectory(file);
                }
            }


            /// <summary>
            /// 通过路径查找文件夹是否存在
            /// </summary>
            /// <param name="filePath"></param>
            /// <returns></returns>
            public static bool ExistsFloder(string filePath)
            {
                return Directory.Exists(filePath);
            }

            public static bool ExistsFloder(string filePath, string fileName)
            {
                return ExistsFloder(Path.Combine(filePath, fileName));
            }

            /// <summary>
            /// 通过路径查找文件是否存在(需要后缀)
            /// </summary>
            /// <param name="filePath"></param>
            /// <returns></returns>
            public static bool ExistsFile(string filePath)
            {
                return File.Exists(filePath);
            }

            public static bool ExistsFile(string filePath, string fileName)
            {
                return ExistsFile(Path.Combine(filePath, fileName));
            }

            /// <summary>
            /// 获取路径文件夹下所有文件夹
            /// </summary>
            /// <param name="path"></param>
            /// <returns></returns>
            public static DirectoryInfo[] GetChildFolders(string path)
            {
                if (!ExistsFloder(path)) return new DirectoryInfo[] { };

                //文件夹下一层的所有文件夹
                //SearchOption.TopDirectoryOnly：这个选项只取下一层的子文件
                //SearchOption.AllDirectories：这个选项会取其下所有的子文件
                DirectoryInfo direction = new DirectoryInfo(path);
                DirectoryInfo[] folders = direction.GetDirectories("*", SearchOption.TopDirectoryOnly);
                return folders;
            }

            public static DirectoryInfo[] GetChildFolders(string path, string name)
            {
                return GetChildFolders(Path.Combine(path, name));
            }

            /// <summary>
            /// 获取路径文件夹下所有文件
            /// </summary>
            /// <param name="path"></param>
            /// <returns></returns>
            public static FileInfo[] GetChildFiles(string path)
            {
                if (!ExistsFloder(path)) return new FileInfo[] { };

                //文件夹下一层的所有子文件
                //SearchOption.TopDirectoryOnly：这个选项只取下一层的子文件
                //SearchOption.AllDirectories：这个选项会取其下所有的子文件
                DirectoryInfo direction = new DirectoryInfo(path);
                FileInfo[] files = direction.GetFiles("*", SearchOption.TopDirectoryOnly);
                return files;
            }

            public static FileInfo[] GetChildFiles(string path, string name)
            {
                return GetChildFiles(Path.Combine(path, name));
            }

            /// <summary>
            /// 获取文件夹下所有特定后缀文件
            /// </summary>
            /// <param name="path"></param>
            /// <param name="suffix"></param>
            /// <returns></returns>
            public static FileInfo[] GetChildFilesWithSuffix(string path, string suffix)
            {
                List<FileInfo> fileInfos = new List<FileInfo>();
                foreach (var f in GetChildFiles(path))
                {
                    if (f.Name.EndsWith(suffix))
                    {
                        fileInfos.Add(f);
                    }
                }

                return fileInfos.ToArray();
            }

            public static FileInfo[] GetChildFilesWithSuffix(string path, string name, string suffix)
            {
                return GetChildFilesWithSuffix(Path.Combine(path, name), suffix);
            }

            /// <summary>
            /// 将文件复制到目标路径
            /// </summary>
            /// <param name="files"></param>
            /// <param name="targetPath">"C:/YourSourceDirectory/"需要以‘/’结尾</param>
            /// <param name="isOverwite">"如果文件已经存在在目标位置，是否覆盖</param>
            public static void CopyFiles(FileInfo[] files, string targetPath, bool isOverwite)
            {
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                    Debug.Log("创建目标路径：" + targetPath);
                }

                foreach (var file in files)
                {
                    string targetFilePath = Path.Combine(targetPath, file.Name);
                    file.CopyTo(targetFilePath, isOverwite);
                }
            }

            /// <summary>
            /// 将文件复制到目标路径
            /// </summary>
            /// <param name="file"></param>
            /// <param name="targetPath">"C:/YourSourceDirectory/"需要以‘/’结尾</param>
            /// <param name="isOverwite">"如果文件已经存在在目标位置，是否覆盖</param>
            public static void CopyFile(FileInfo file, string targetPath, bool isOverwite)
            {
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                    Debug.Log("创建目标路径：" + targetPath);
                }

                string targetFilePath = Path.Combine(targetPath, file.Name);
                file.CopyTo(targetFilePath, isOverwite);
            }


            /// <summary>
            /// 异步获取Resources或persistentDataPath相对路径下的文件
            /// </summary>
            /// <param name="finishedFilePath">相对路径，例如“txt/love2000”</param>
            /// <param name="suffix">文件后缀，默认为“.txt”</param>
            public async UniTask<string> LoadSubtitles(string finishedFilePath, string suffix = ".txt")
            {
                string content = "";
                if (Resources.Load<TextAsset>(finishedFilePath) != null)
                    content = Resources.Load<TextAsset>(finishedFilePath).text;
                else
                    content = await LoadTextFromFileAsync(finishedFilePath + suffix);
                return content;
            }

            /// <summary>
            /// 异步获取指定路径下的文本文件，返回一个string
            /// </summary>
            /// <param name="fileName">文件名称，需要带后缀</param>
            /// <param name="path">默认为persistentDataPath，如需修改可以手动填写</param>
            /// <returns></returns>
            public async UniTask<string> LoadTextFromFileAsync(string fileName, string path = "")
            {
                string filePath = Path.Combine(path == "" ? Application.persistentDataPath : path, fileName);

                if (File.Exists(filePath))
                {
                    // 使用异步读取文件内容
                    using (var streamReader = new StreamReader(filePath))
                    {
                        return await streamReader.ReadToEndAsync();
                    }
                }
                else
                {
                    Debug.Log($"File not found: {filePath}");
                    return null;
                }
            }

            /// <summary>
            /// 将文本写入文件
            /// </summary>
            /// <param name="filePath">从项目文件夹起的路径：例如"Assets/Resources/txtFile.txt"</param>
            /// <param name="str">写入文件的内容</param>
            public static void TextWriteIn(string filePath,string str)
            {
                File.WriteAllText(filePath, str);
            }
        }
    }
}